package io.process.plus.output;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * 输出解析线程
 * 
 * @author baochunliang
 * @date 2015/07/04
 */
public class OutputParserJob extends Thread {
    /**
     * 输出解析器
     */
    private OutputParser parser;

    /**
     * 字符集（不填默认为当前系统字符集）
     */
    private String charsetName;

    /**
     * Process对象
     */
    private Process process;

    /**
     * 是否已经取消了任务执行
     */
    private boolean jobCanceled;

    /**
     * 构造函数
     * 
     * @param parser
     * @param process
     * @param charsetName
     */
    public OutputParserJob(OutputParser parser, Process process, String charsetName) {
        this.parser = parser;
        this.process = process;
        this.charsetName = charsetName;
    }

    @Override
    public void run() {
        BufferedReader br = null;

        // 按行读取
        br = new BufferedReader(new InputStreamReader(process.getInputStream(),
            Charset.forName(charsetName == null ? System.getProperty("sun.jnu.encoding") : charsetName)));
        try {
            String line = null;
            while ((line = br.readLine()) != null) {
                if (parser != null) {
                    int status = parser.parse(line.trim());

                    // 取消任务
                    if (status == OutputParser.STATUS_CANCEL) {
                        System.out.println("主动取消命令执行");
                        jobCanceled = true;
                        process.destroy();
                        return;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 命令是否取消执行
     * 
     * @return
     */
    public boolean isJobCanceled() {
        return jobCanceled;
    }
}